package com.zhenyi.youqu.miniapp;

import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.youqu.common.model.YqMessage;
import com.youqu.common.model.YqUser;
import com.youqu.common.model.YqUserAddress;
import com.youqu.common.model.YqUserSubscribe;
import com.youqu.common.model.YqUserSubscribeProduct;
import com.zhenyi.youqu.core.YQMiniAppController;
import com.zhenyi.youqu.interceptor.YQUserInterceptor;

public class UserController extends YQMiniAppController {

	/**
	 * 个人资料
	 */
	@Before({ YQUserInterceptor.class })
	@Override
	public void index() {
		YqUser user = getUser();
		// user.updateOrderCount();
		user.put("groupCount",
				db.find(db.getSqlPara("YQOrderGroupCardProduct", Kv.by("userId", user.getId()).set("isGroup", 1)))
						.size());
		user.put("cardCount", db
				.find(db.getSqlPara("YQOrderGroupCardProduct", Kv.by("userId", user.getId()).set("isCard", 1))).size());
		user.put("productCount",
				db.find(db.getSqlPara("YQOrderGroupCardProduct", Kv.by("userId", user.getId()).set("isProduct", 1)))
						.size());
		user.put("orderCount", db.find(db.getSqlPara("YQAllOrder", Kv.by("userId", user.getId()))).size());
		user.put("favoriteCount", db.find(db.getSqlPara("YQProductSubscribes", Kv.by("userId", user.getId()))).size());
		renderSuccess(user);
	}

	/**
	 * 更新用户信息
	 */
	@Before({ YQUserInterceptor.class })
	@Override
	public void update() {
		YqUser user = getUser();
		String country = getPara("country");
		Integer gender = getParaToInt("gender");
		String province = getPara("province");
		String avatarUrl = getPara("avatarUrl");
		String nickName = getPara("nickName");

		if (StrKit.notBlank(avatarUrl)) {
			user.setAvatarUrl(avatarUrl);
		}
		if (StrKit.notBlank(nickName)) {
			user.setNickName(nickName);
		}
		if (gender != null) {
			user.setGender(gender);
		}
		if (StrKit.notBlank(country)) {
			user.setCountry(country);
		}
		if (StrKit.notBlank(province)) {
			user.setProvince(province);
		}
		user.update();
		renderSuccess();
	}

	/**
	 * 个人消息
	 */
	public void message() {
		YqUser user = getUser();
		Long userId = user.getId();
		Kv kv = Kv.by("userId", userId);
		SqlPara sqlPara = db.getSqlPara("YQFindUserMessages", kv);
		Page<YqMessage> pages = YqMessage.dao.paginate(getPage(), PAGE_SIZE, sqlPara);
		renderPage(pages);
	}

	public void readMsg() {
		Long id = getParaToLong("id");
		YqMessage msg = YqMessage.dao.findById(id);
		if (msg != null) {
			msg.setIsNew(0);
			msg.update();
		}
		renderSuccess();
	}

	public void updateMobile() {
		String mobile = getPara("mobile");
		YqUser user = getUser();
		user.setMobile(mobile);
		user.update();
		renderSuccess();
	}

	/**
	 * 地址列表
	 */
	public void address() {
		YqUser user = getUser();
		if (user == null) {
			renderFailure(401, "please login");
			return;
		}
		SqlPara sqlPara = db.getSqlPara("YQUserAddress", Kv.by("userId", user.getId()));
		List<YqUserAddress> list = YqUserAddress.dao.find(sqlPara);
		renderResult(list);
	}

	/**
	 * 地址信息
	 */
	public void addressInfo() {
		Long addressId = getParaToLong("addressId");
		YqUserAddress info = YqUserAddress.dao.findById(addressId);
		if (info == null) {
			info = new YqUserAddress();
		}
		renderResult(info);
	}

	/**
	 * 更新收货地址
	 */
	public void updateAddress() {
		YqUser user = getUser();
		if (user == null) {
			renderFailure(401, "please login");
			return;
		}
		Long addressId = getParaToLong("addressId");
		String address = getPara("address");
		String mobile = getPara("mobile");
		String name = getPara("name");
		String postcode = getPara("postcode");

		YqUserAddress info;
		if (addressId == null) {
			info = new YqUserAddress();
			info.setUserId(user.getId());
			info.save();
		} else {
			info = YqUserAddress.dao.findById(addressId);
			if (info == null) {
				renderError(404);
				return;
			}
			if (!info.getUserId().equals(user.getId())) {
				renderFailure();
				return;
			}
		}

		info.setAddress(address);
		info.setMobile(mobile);
		info.setName(name);
		info.setPostcode(postcode);
		renderFlag(info.update());
	}

	/**
	 * 删除收货地址
	 */
	public void deleteAddress() {
		YqUser user = getUser();
		if (user == null) {
			renderFailure(401, "please login");
			return;
		}
		Long addressId = getParaToLong("addressId");
		if (addressId == null) {
			renderFailure("address id is required");
			return;
		}
		YqUserAddress info = YqUserAddress.dao.findById(addressId);
		if (info == null) {
			renderError(404);
			return;
		}
		if (!info.getUserId().equals(user.getId())) {
			renderFailure();
			return;
		}
		renderFlag(info.delete());
	}

	/**
	 * 更新位置信息
	 */
	public void updateLocation() {
		renderSuccess();
		String latitude = getPara("latitude");
		String longitude = getPara("longitude");
		if (StrKit.notBlank(latitude, longitude)) {
			YqUser user = getUser();
			if (user == null) {
				return;
			}
			user.setLatitude(latitude);
			user.setLongitude(longitude);
			user.update();
		}
	}

	/**
	 * 喜欢
	 */
	@Before({ YQUserInterceptor.class })
	public void subscribe() {
		YqUser user = getUser();
		Long itemId = getParaToLong("itemId");
		Long productId = getParaToLong("productId");
		Long userId = user.getId();
		if (itemId != null) {
			YqUserSubscribe userSubscribe = YqUserSubscribe.dao.findById(itemId, userId);
			if (userSubscribe == null) {
				userSubscribe = new YqUserSubscribe();
				userSubscribe.setUserId(userId);
				userSubscribe.setItemId(itemId);
				userSubscribe.save();
			}
		} else if (productId != null) {
			YqUserSubscribeProduct userSubscribeProduct = YqUserSubscribeProduct.dao.findById(productId, userId);
			if (userSubscribeProduct == null) {
				userSubscribeProduct = new YqUserSubscribeProduct();
				userSubscribeProduct.setUserId(userId);
				userSubscribeProduct.setProductId(productId);
				userSubscribeProduct.save();
			}
		}
		renderSuccess();
	}

	/**
	 * 取消喜欢
	 */
	@Before({ YQUserInterceptor.class })
	public void unsubscribe() {
		YqUser user = getUser();
		Long itemId = getParaToLong("itemId");
		Long productId = getParaToLong("productId");
		Long userId = user.getId();
		if (itemId != null) {
			YqUserSubscribe userSubscribe = YqUserSubscribe.dao.findById(itemId, userId);
			if (userSubscribe == null) {
				renderFailure(404, "not found");
				return;
			}
			userSubscribe.delete();
		} else if (productId != null) {
			YqUserSubscribeProduct userSubscribeProduct = YqUserSubscribeProduct.dao.findById(productId, userId);
			if (userSubscribeProduct == null) {
				renderFailure(404, "not found");
				return;
			}
			userSubscribeProduct.delete();
		}
		renderSuccess();
	}

	/**
	 * 收藏商品列表
	 */
	@Before({ YQUserInterceptor.class })
	public void subscribeProducts() {
		YqUser user = getUser();
		if (user == null) {
			renderFailure(401, "Please login");
			return;
		}
		Kv kv = Kv.create();
		kv.set("userId", user.getId());
		SqlPara sqlPara = db.getSqlPara("YQProductSubscribes", kv);
		Page<Record> pages = db.paginate(getPage(), PAGE_SIZE, sqlPara);
		renderPage(pages);
	}
}
